#include <sstream>
#include "TcpSocket.hpp"

int main(int argc, char* argv[]){
  if(argc < 3){
    printf("[ip] [port] Not Set\n");
    return 0;
  }
  std::string svr_ip = argv[1];
  uint16_t svr_port = atoi(argv[2]);
  TcpSocket Svr;
  if(!Svr.CreateSocket()){
    return 0;
  }
  if(!Svr.Bind(svr_ip, svr_port)){
    return 0;
  }
  if(!Svr.Listen()){
    return 0;
  }
  while(1){
    std::string recv_buf;
    sockaddr_in cli_addr;
    TcpSocket cli_sock;
    if(!Svr.Accept(cli_sock, cli_addr)){
      printf("Accept error!\n");
      continue;
    }
    printf("Client IP:%s port:%u\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
    while(1){
      if(!cli_sock.Recv(recv_buf)){
        printf("Client disconnect\n");
        break;
      }
      std::string body("<html><h1>Hellow World</h1></html>");
      std::cout<<"Chrome Send Data:"<<recv_buf<<std::endl;
      std::stringstream ss;
      ss << "HTTP/1.1 200 OK\r\n";
      ss << "Content-Length: " << body.size() << "\r\n";
      ss << "Content-Type: text/html\r\n";
      ss << "\r\n";
      std::string header(ss.str());
      cli_sock.Send(header);
      cli_sock.Send(body);
    }   
    cli_sock.Close();
  }
  Svr.Close();
  return 0;
}
